package com.juhuixing.file.server.business.service.impl;

import com.juhuixing.common.assembly.redis.SnowflakeIdWorker;
import com.juhuixing.common.constant.QiNiuConstant;
import com.juhuixing.common.enums.SpaceEnum;
import com.juhuixing.common.utils.ExceptionHandler;
import com.juhuixing.common.utils.qiniu.QiniuOperateUtil;
import com.juhuixing.file.server.business.service.IFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 *@ClassName FileServiceImpl
 *@Description TODO
 *@Author 刘猛
 *@Date 2019/3/20 10:50
 **/
@Slf4j
@Service
public class FileServiceImpl implements IFileService {
    @Override
    public String upload(MultipartFile file,String type) {
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String resultUrl = null;
        fileName = fileName.substring(0,fileName.lastIndexOf(".")) +"-"+ SnowflakeIdWorker.generateId() + fileType;
        try {
            /**上传到共有云**/
            if(StringUtils.equals(type, SpaceEnum.PUBLIC.getType())){
                QiniuOperateUtil.uploadFileToOpenSpace(file.getBytes(),fileName);
                resultUrl = QiNiuConstant.QI_NIU_OPEN_ADDRESS + fileName;
            }
            /**上传到私有云**/
            else if(StringUtils.equals(type, SpaceEnum.PRIVATE.getType())){
                QiniuOperateUtil.uploadFileToPrivateSpace(file.getBytes(),fileName);
                resultUrl = QiNiuConstant.QI_NIU_PRIVATE_ADDRESS + fileName;
            }
        } catch (IOException e) {
            log.error(ExceptionHandler.getErrorInfoFromException(e));
            return null;
        }
        return resultUrl;
    }
}
